package org.example.c_0_008;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

public class T_SynchronizedMap {

    public static void main(String[] args) throws InterruptedException {
        /*
         * 准备元数据
         */
        Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());
        CountDownLatch putCountDownLatch = new CountDownLatch(100);
        CountDownLatch getCountDownLatch = new CountDownLatch(100);
        String[] uuids = new String[T_MapConfig.LENGTH * T_MapConfig.MAX];
        for (Integer i = 0; i < T_MapConfig.LENGTH * T_MapConfig.MAX; i++) {
            uuids[i] = UUID.randomUUID().toString();
        }
        /*
         * 测试开始
         */
        long start = System.currentTimeMillis();
        for (Integer i = 0; i < T_MapConfig.MAX; i++) {
            Integer finalI = i;
            new Thread(() -> {
                int startIndex = finalI * T_MapConfig.LENGTH;
                int endIndex = startIndex + T_MapConfig.LENGTH;
                for (; startIndex < endIndex; startIndex++) {
                    map.put(uuids[startIndex], uuids[startIndex]);
                }
                putCountDownLatch.countDown();
            }).start();
        }
        putCountDownLatch.await();
        System.out.println("写用时："+(System.currentTimeMillis()-start));

        start = System.currentTimeMillis();
        for (Integer i = 0; i < T_MapConfig.MAX; i++) {
            Integer finalI = i;
            new Thread(() -> {
                int startIndex = finalI * T_MapConfig.LENGTH;
                int endIndex = startIndex + T_MapConfig.LENGTH;
                for (; startIndex < endIndex; startIndex++) {
                    String s = map.get(uuids[startIndex]);
                }
                getCountDownLatch.countDown();
            }).start();
        }
        getCountDownLatch.await();
        System.out.println("读用时："+(System.currentTimeMillis()-start));
        System.out.println("map大小："+map.keySet().size());
    }
}
